package com.document;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.DBHelper.MySQLIteOpenHelper;
import com.document.MyFile.ListVIewAdapter.ViewHolder;
//我的文档视图类  显示扫描得到的PDF Word Excel 文档 并且调用自身程序读取文档 
public class MyFile extends MyActivity {
	private ListView filelist;
	private static  ListVIewAdapter ladapter; 
	private List returnList;
	private List<Boolean> boolList = new ArrayList<Boolean>();
	boolean visflag = false; //  显示checkbox
	  ProgressDialog progressdialog; //删除文件进度对话框
	
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);	
		
		setContentView(R.layout.myfile);
		 MySQLIteOpenHelper helper=new MySQLIteOpenHelper(getApplicationContext());
			//查询获得游标
			 returnList = helper.select("select * from ListFile ", null);
			 //若为空 提示先导入数据
			 if(returnList.size()==0){
				 Toast.makeText(getApplicationContext(), "数据为空，请先导入...", Toast.LENGTH_LONG).show();
				
			 }
			 else{
				 //向boolList加入boolean数据  处理文件删除 判断列表文件是否被选则
			 for(int i=0;i<returnList.size();i++)
			 {
				 boolList.add(false); 
			 }
			 System.out.println("size"+returnList.size());
			 //实例ListVIewAdapter类
			 ladapter = new ListVIewAdapter(this);    
	            
			 filelist = (ListView)findViewById(R.id.listView1);  
			 //为filelist配置适配器
			 filelist.setAdapter(ladapter);    
		          
			 filelist.setScrollBarStyle(1);  
		//设置短按单击事件 若checkbox显示 处理删除事件  不显示 处理文件读取事件	 
		filelist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				//如果checkbox显示 处理批量删除
			    if(visflag)  
                {  
                    ViewHolder viewHolder = (ViewHolder) arg1.getTag();  
                    viewHolder.cb.toggle();  
                    if(viewHolder.cb.isChecked())  
                    {  
  
                        boolList.set(arg2, true);  
                    }
                }
			    //checkbox未显示，处理打开文件
			    else{
					  HashMap<String,String> map=(HashMap<String,String>)arg0.getItemAtPosition(arg2); 
				        String path=map.get("ListFile_Name");
				        if(getFile(path,"txt") )
				        {
				        	startActivity(getFileIntent.getTxtFileIntent(path));
				        
				        }else if(getFile(path,"xls"))
				        		{
				        	startActivity(getFileIntent.getExcelFileIntent(path));
				        	
				        		}
				        else if(getFile(path,"pdf"))
		        		{
		        	startActivity(getFileIntent.getPdfFileIntent(path));
		        	finish();
		        		}
				        else if(getFile(path,"html"))
		        		{
		        	startActivity(getFileIntent.gethtmlFileIntent(path));	
		        	
		        		}
				        else{
				        	startActivity(getFileIntent.getWordFileIntent(path));
				        	
				        }
				        System.out .println("path"+path);				 
			}}
		});
		helper.close();
	}
		if(returnList.size()>0)
		{
				//添加长按点击   弹出选择菜单
			 filelist.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {   	               
		            @Override  
		            public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {   
		                menu.setHeaderTitle("请选择...");  
		                menu.add(0, 0, 0, "打开"); 
		                menu.add(0, 1, 0, "删除");   
		                menu.add(0, 2, 0, "发送"); 
		                
		            }   
		        });    
		    }  }     
		    //长按菜单响应函数   
		    @Override  
		    public boolean onContextItemSelected(MenuItem item) { 
		    	 ContextMenuInfo info = item.getMenuInfo();
		    	AdapterView.AdapterContextMenuInfo contextMenuInfo = (AdapterContextMenuInfo) info;
		    	  // 获取选中行位置
		    	  int position = contextMenuInfo.position;
		    	  HashMap<String,String> map=(HashMap<String, String>) returnList.get(position); 
			        String path=map.get("ListFile_Name");
		    	switch(item.getItemId())
		    	{
		    	case 0://打开
		    	{
		    		
				        if(getFile(path,"txt") )
				        {
				        	startActivity(getFileIntent.getTxtFileIntent(path));
				        
				        }else if(getFile(path,"xls"))
				        		{
				        	startActivity(getFileIntent.getExcelFileIntent(path));	
				        	
				        		}
				        else if(getFile(path,"pdf"))
		        		{
		        	startActivity(getFileIntent.getPdfFileIntent(path));	
		        	finish();
		        		}
				        else if(getFile(path,"html"))
		        		{
		        	startActivity(getFileIntent.gethtmlFileIntent(path));	
		        	
		        		}
				        else{
				        	startActivity(getFileIntent.getWordFileIntent(path));	
				        
				        }	
				        break;
		    	}
		       case  1:{
		    	   boolList.remove(position);  
                   returnList.remove(position); 
                   //删除数据库中数据
                   MySQLIteOpenHelper helper=new MySQLIteOpenHelper(getApplicationContext());
                   String delsql="delete from ListFile where ListFile_Name='"+path+"'";
                   helper.delete(delsql);
                   this.ladapter.notifyDataSetInvalidated(); 
                  
                   break;
		       }

		    	case 2:{
		    		//调用系统分享功能
		    		 Intent intent = new Intent(Intent.ACTION_SEND);  
		                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));   
		                intent.setType("*/*");   //分享文件  
		                startActivity(Intent.createChooser(intent,"分享"));
		    		break;
		    	} 
		    } 
		    	return super.onContextItemSelected(item);   
		    	}		 
	//为listView设置适配器
	 class ListVIewAdapter extends BaseAdapter    
	    {    
	            
	        Context c;    
	        LayoutInflater mInflater ;    
	        ListVIewAdapter(Context context)    
	        {    
	            c = context;    
	            mInflater = getLayoutInflater();    
	        }    
	        @Override    
	        public int getCount()    
	        {    
	            return returnList.size();    
	        }    
	    
	        @Override    
	        public Object getItem(int position)    
	        {    
	            return returnList.get(position);    
	        }    
	    
	        @Override    
	        public long getItemId(int position)    
	        {    
	            return position;    
	        }    
	            
	    
	        @Override    
	        public View getView(final int position, View convertView,    
	                ViewGroup parent)    
	        {    
	            ViewHolder holder = null ;    
	            if(convertView == null)    
	            {    
	                  
	                holder = new ViewHolder();  
	                convertView  = mInflater.inflate(R.layout.filelistitem, null);  
	                holder.tv = (TextView)convertView.findViewById(R.id.lisat);    
	                holder.cb = (CheckBox)convertView.findViewById(R.id.checkBox);  
	                convertView.setTag(holder);  
	                  
	            }else{  
	                holder = (ViewHolder) convertView.getTag();  
	            }   
	            HashMap<String,String> map=(HashMap<String, String>) returnList.get(position); 
		        String path=map.get("ListFile_Name");
	            holder.tv.setText(path);    
	            holder.cb.setChecked(boolList.get(position));    
	                
	            if(visflag)    
	            {    
	                holder.cb.setVisibility(View.VISIBLE);    
	            }    
	            else    
	            {    
	                holder.cb.setVisibility(View.INVISIBLE);    
	            }    
	            
	            return convertView;    
	        }    
	        class ViewHolder    
	        {    
	            TextView tv;    
	            CheckBox cb;    
	        }    
	            
	    }  
	 // 用Handler来更新UI 实现文件删除
	     Handler handler = new Handler(){  
	  
	        @Override  
	        public void handleMessage(Message msg) {  
	              
	            //关闭ProgressDialog  
	            progressdialog.dismiss();  
	              
	            //更新UI  
	          ladapter.notifyDataSetChanged();  
	            Toast.makeText(getApplicationContext(), "删除成功...", Toast.LENGTH_LONG).show();
	           
	            
	        }};  
	 //添加批量删除菜单
	 public boolean onCreateOptionsMenu(Menu menu)    
	    {    
	            
	        menu.add(0, 0, 0, "批量删除");    
	        menu.add(0, 1, 0, "确定删除");    	          
	        menu.add(0, 2, 0, "全选");    	          
	        return super.onCreateOptionsMenu(menu);    
	    }    
	    
	    @Override    
	    public boolean onOptionsItemSelected(MenuItem item)    
	    {    
	        switch(item.getItemId())    
	        {    
	            case 0:  // 批量处理    
	                {    
	                    
	                        visflag = true;    
	                        
	                    this.ladapter.notifyDataSetInvalidated();    
	                    break;    
	                }    
	            case 1: //确定删除    
	            	
	                {  
	                	//判断如果boollist内有数据并且初始
	                	if(selectitem())
	                		{progressdialog = ProgressDialog.show(MyFile.this, "正在删除...", "请稍后...", true, false);
	              
	                new Thread( new Runnable() {
						public void run() {
							
			                        if(visflag)  
			                        {  
			                            for(int location=0; location<boolList.size(); )  
			                            {  
			                                if(boolList.get(location))  
			                                {  
			                                    boolList.remove(location);  
			                                    returnList.remove(location); 
			                                    HashMap<String,String> map=(HashMap<String, String>) returnList.get(location); 
			                    		        String path=map.get("ListFile_Name");
			                                    //删除数据库中数据
			                                    MySQLIteOpenHelper helper=new MySQLIteOpenHelper(getApplicationContext());
			                                    String delsql="delete from ListFile where ListFile_Name='"+path+"'";
			                                    helper.delete(delsql);
			                                    visflag=false;
			                                    continue;  
			                                }  
			                                location++;  
			                            }  
			                        }  
			                        //向handler发消息  
			                        handler.sendEmptyMessage(0);    
			                    }  				
					}
	                ).start(); 
	              
	                		}
	                	else{
	                		Toast.makeText(getApplicationContext(), "请先选择要删除的条目", Toast.LENGTH_LONG).show();
	                		
	                	}
	               
	                   // this.ladapter.notifyDataSetChanged();  
	                    break;    
	                } 
	                
	            case 2:  // 全选    
	                {    if(visflag)
	                {
	                    for(int i=0;i<boolList.size()-1;i++)
	                    {
	                    	 boolList.set(i, true);  
	                    }
	                        
	                    this.ladapter.notifyDataSetInvalidated();    
	                    break;    
	                }    
	        }    }
	        return super.onOptionsItemSelected(item);    
	    }    
	    //判断是否有选择删除的条目
	    private boolean selectitem(){
	    	boolean re=false;
	    	for(int i=0;i<boolList.size();i++)
	    	{
	    		if(boolList.get(i))
	    		{
	    			re=true;
	    			break;
	    		}
	    		else{
	    			re=false;
	    		}
	    	}
	    		
			return re;
	    	
	    }
	private boolean getFile(String fName,String filetype) {
		boolean re;
		//取得文件拓展名
		String end=fName.substring(fName.lastIndexOf(".")+1,
		fName.length()).toLowerCase();
		//根据拓展名类型决定打开方式
		if(end.equals(filetype))
		{
			re=true;
		}
		else{
			re=false;
		}
		return re;
	}
   
	
}
